#!/usr/bin/env node

/*
免登录截图：
先在chrome浏览器中登录网站
百度文库截图
*{background: white !important}
document.getElementById('app').style.display='none';
document.body.appendChild(document.getElementById('original-pageNo-1'));
document.body.removeChild(document.getElementById('pageNo-2'));
*/

const utils = require('./js/utils');
// const executablePath = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const executablePath = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe';

function getCookies(url, isEdge = true) {
    return new Promise(resolve => {
        require(isEdge ? './edge-cookies-secure.js' : 'chrome-cookies-secure').getCookies(url, 'puppeteer', function (err, cookies) {
            resolve(cookies);
        });
    });
}
async function autoScroll(page) {
    return page.evaluate(() => {
        return new Promise((resolve, reject) => {
            //滚动的总高度
            var totalHeight = 0;
            //每次向下滚动的高度 100 px
            var distance = 100;
            var timer = setInterval(() => {
                //页面的高度 包含滚动高度
                var scrollHeight = document.body.scrollHeight;
                //滚动条向下滚动 distance
                window.scrollBy(0, distance);
                totalHeight += distance;
                //当滚动的总高度 大于 页面高度 说明滚到底了。也就是说到滚动条滚到底时，以上还会继续累加，直到超过页面高度
                if (totalHeight >= scrollHeight) {
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        })
    });
}
async function screenshot(url, file, selector, width, height) {
    width = +(width || 1920);
    height = +(height || 900);
    console.log("[screenshot]: ", { url, file, selector, width, height });
    const cookies = await getCookies(url);
    const browser = await require('puppeteer').launch({
		headless: false, // 开启界面
		devtools: false, // 自动开启 F12
		executablePath,
	});
    const page = await browser.newPage();
    await page.setCookie(...cookies);
    await page.setViewport({ width, height });
    await page.goto(url);
    await utils.sleep(100000);
    let target = page;
    if (selector) {
        await page.waitForSelector(selector);
        target = await page.$(selector);
    }
    await autoScroll(page);
    await target.screenshot({ path: file });
    await page.close();
    await browser.close();
}
async function screenshotForPage(url, pages, width, height) {
    width = +(width || 945);
    height = +(height || 1257);
    pages = (pages || '').split(/,|，|;|；/).filter(Boolean);
    const list = [];
    for (const page of pages) {
        const ps = page.split('-');
        if (ps.length > 1) {
            for (let i = +ps[0]; i <= +ps[1]; i++) {
                list.push(i);
            }
        } else {
            list.push(+ps);
        }
    }
    pages = [...new Set(list)].sort();
    console.log("[screenshotForPage]: ", { url, pages, width, height });
    const cookies = await getCookies(url);
    const browser = await require('puppeteer').launch();
    const page = await browser.newPage();
    await page.setCookie(...cookies);
    await page.setViewport({ width, height });
    await page.goto(url);
    await page.addStyleTag({ content: '*{background: white !important}' });
    await page.waitForTimeout(1000);
    await autoScroll(page);
    await page.click('.read-all');
    await page.waitForTimeout(1000);
    await autoScroll(page);
    await page.waitForTimeout(1000);
    for (let i of pages) {
        console.log(`start pageNo-${i}`);
        await page.evaluate((i) => {
            document.getElementById('app').style.display = 'none';
            i > 1 && document.body.removeChild(document.getElementById(`original-pageNo-${i - 1}`));
            document.body.appendChild(document.getElementById(`original-pageNo-${i}`));
        }, i);
        await page.screenshot({ path: `${i}.png` });
        console.log(`end pageNo-${i}`);
    }
    await page.close();
    await browser.close();
}

function main() {
    const param1 = process.argv[2];
    const param2 = process.argv[3];
    if (param1 === '-h' || param1 === '--help' || !param1) {
        console.log('   网页截图：');
        console.log('   命令：xscreenshot url file [selector] width height');
        console.log('   百度文库截图：');
        console.log('    命令：xscreenshot url [1,2-5] width height');
        console.log('');
        return;
    }
    if (/\.(png|jpg)$/.test(param2)) {
        screenshot(...process.argv.slice(2));
    } else {
        screenshotForPage(...process.argv.slice(2));
    }
}

main();
